package com.sven.hello;

import com.netflix.zuul.FilterFileManager;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.groovy.GroovyCompiler;
import com.netflix.zuul.groovy.GroovyFileFilter;
import com.sven.hello.config.FilterConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

import java.io.File;

@EnableZuulProxy
@SpringBootApplication
public class ApiGatewayFilterApplication {

	public static void main(String[] args) {
		SpringApplication.run(ApiGatewayFilterApplication.class, args);
		// new ApiGatewayFilterApplication().getMyDIR();


	}

	/**
	 * api网关应用会每隔5秒，从api网关服务所在位置的 filter/pre 和 filter/post 目录下获取Groovy定义的过滤器，
	 * 并对其进行编译和动态加载使用。
	 *
	 * @param filterConfiguration
	 * @return
	 */
	@Bean
	public FilterLoader filterLoader (FilterConfiguration filterConfiguration) {
		FilterLoader filterLoader = FilterLoader.getInstance();
		filterLoader.setCompiler(new GroovyCompiler());
		try {
			FilterFileManager.setFilenameFilter(new GroovyFileFilter());
			FilterFileManager.init(
					filterConfiguration.getInterval(),
					filterConfiguration.getRoot() + "/pre",
					filterConfiguration.getRoot() + "/post");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return filterLoader;
	}

	public  void getMyDIR(){//获取当前类文件的绝对路径
		//ApiGatewayFilterApplication
		//E:\ideaworkspace\springclouddemo3\api-gateway-dynamic-filter\target\classes\com\sven\hello
		File file = new File(this.getClass().getResource("").getPath());
		System.out.println(file);
		String url = this.getClass().getClassLoader().getResource("").getPath();
		System.out.println(url);
	}

}
